package org.tom.pet.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tom.basic.exception.MyException;
import org.tom.basic.service.impl.BaseServiceImpl;
import org.tom.basic.util.JsonResult;
import org.tom.basic.util.PageList;
import org.tom.pet.domain.Pet;
import org.tom.pet.domain.PetDetail;
import org.tom.pet.mapper.PetDetailMapper;
import org.tom.pet.mapper.PetMapper;
import org.tom.pet.query.PetQuery;
import org.tom.pet.service.IPetService;
import org.tom.user.domain.UserAddress;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class PetServiceImpl  extends BaseServiceImpl<Pet> implements IPetService {

    @Autowired
    private PetMapper petMapper;
    @Autowired
    private PetDetailMapper petDetailMapper;

    @Override
    public void insert(Pet pet) {
        // 将宠物信息存入数据库，返回自增主键
        petMapper.add(pet);
        // 通过pet对象中的Detail字段获取PetDetail对象
        PetDetail detail = pet.getDetail();
        // 获取pet的自增主键
        detail.setPet_id(pet.getId());
        // PetDetail存入数据库
        petDetailMapper.add(detail);

    }

    /**
     * 宠物上架处理
     * @param petId
     * @return
     */
    @Override
    public JsonResult onsale(List<Long> petIds) {
        // 判断参数非空
        if (petIds==null){
            throw new MyException("非法请求");
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("onsaleTime", new Date());
        map.put("ids", petIds);
        petMapper.onsale(map);
        return JsonResult.me();
    }

    /**
     * 下架处理
     * @param petIds
     * @return
     */
    @Override
    public JsonResult offsale(List<Long> petIds) {

        if (petIds==null){
            throw new MyException("非法请求");
        }

        HashMap<String, Object> map = new HashMap<>();
        //map.put("time", "offsaletime"); // 当两个updata放在一起是就可以用${time}里面多传一个参数就可以区分
        map.put("offsaletime", new Date());
        map.put("ids", petIds);
        petMapper.offSale(map);
        return JsonResult.me();
    }

    @Override
    public PageList<Pet> loadPetAll(PetQuery query) {
        PageList<Pet> petPageList = super.queryList(query);
        return petPageList;
    }

    @Override
    public JsonResult loadOnPetByPetId(Long id, Long online) {
        Pet pet1 = petMapper.loadById(id);
        if (pet1.getState()==0){ // 通过地址栏访问未上架的商品
            throw new MyException("非法请求");
        }
        Pet pet = petMapper.loadPetByStateAndId(id,online);
        return JsonResult.me().setResultObj(pet);
    }

    @Override
    public JsonResult getAddress(Long id) {
        UserAddress userAddress = petMapper.getAddress(id);
        return JsonResult.me().setResultObj(userAddress);
    }
}
